package org.example.classtopia.Controller;

import org.example.classtopia.Common.Result.Result;
import org.example.classtopia.Service.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/posts/{postId}/likes")
public class  PostLikeController {

    @Autowired
    private PostLikeService postLikeService;

    @PostMapping
    public Result<Boolean> likePost(@PathVariable Long postId, @RequestParam Long userId) {
        try {
            boolean result = postLikeService.likePost(userId, postId);
            if (result) {
                return Result.success("点赞成功", true);
            } else {
                return Result.error(500, "点赞失败");
            }
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    @DeleteMapping
    public Result<Boolean> unlikePost(@PathVariable Long postId, @RequestParam Long userId) {
        try {
            boolean result = postLikeService.unlikePost(userId, postId);
            if (result) {
                return Result.success("取消点赞成功", true);
            } else {
                return Result.error(500, "取消点赞失败");
            }
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    @GetMapping("/status")
    public Result<Boolean> hasLiked(@PathVariable Long postId, @RequestParam Long userId) {
        try {
            boolean result = postLikeService.hasLiked(userId, postId);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    @GetMapping("/count")
    public Result<Integer> countLikes(@PathVariable Long postId) {
        try {
            int count = postLikeService.countLikes(postId);
            return Result.success("查询成功", count);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }
}

